package cn.itsource.hrm.handler;

import cn.itsource.hrm.dto.EmailMessageDTO;
import cn.itsource.hrm.dto.SMSMessageDTO;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

import static cn.itsource.hrm.constant.MQConstant.QUEUE_INFORM_EMAIL;
import static cn.itsource.hrm.constant.MQConstant.QUEUE_INFORM_SMS;

@Component
@Slf4j
public class CourseMQListener {

    @RabbitListener(queues = QUEUE_INFORM_SMS )
    public void smsListener(Channel channel
            , Message message
            , @Payload SMSMessageDTO smsMessage){
        List<String> phones = smsMessage.getPhones();
        String content = smsMessage.getContent();
        phones.forEach(p->{
            log.info("短信： " +p + ":"+ content);
        });
        ack(channel, message);
    }

    @RabbitListener(queues = QUEUE_INFORM_EMAIL )
    public void emailListener(Channel channel
            , Message message
            , @Payload EmailMessageDTO smsMessage){
        List<String> email = smsMessage.getUrl();
        String content = smsMessage.getContent();
        email.forEach(p->{
            log.info("Emial： " +p + ":"+ content);
        });
        ack(channel, message);
    }

    private void ack(Channel channel, Message message) {
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
